package com.apache.common.plugins.dict;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据字典操作：增删改特殊控制插件，包含dictCate和dictItem两表插件
 */
public class DictOperatePluginImpl implements CustomMethodPlugin {
    protected Logger log = Logger.getLogger(getClass());
    @Override
    public Object beforeInvoke(Map<String, Object> param) {
        Map<String,String> typeMap = new HashMap<String, String>();
        typeMap.put("i_dictDataCate","科目.新增");
        //typeMap.put("u_dictDataCate","科目.修改");
        typeMap.put("d_dictDataCate","科目.删除");
        typeMap.put("i_dictDataItem","科目下条目.新增");
        typeMap.put("u_dictDataItem","科目下条目.修改");
        typeMap.put("d_dictDataItem","科目下条目.删除");
        String modelTypes = String.valueOf(param.get("modelTypes"));
        if(!typeMap.containsKey(modelTypes)){
            log.error("操作类型不支持："+modelTypes);
            throw new BusinessException("操作类型不支持");
        }

        Map<String,Object> whereMap = new HashMap<String,Object>();
        if("i_dictDataCate".equals(modelTypes)){
            String cateEname = String.valueOf(param.get("dictDataCate.cateEname"));
            log.info("数据字典["+cateEname+"]["+typeMap.get(modelTypes)+"]->"+modelTypes);
            whereMap.put("dictDataCate.w_cateEname",cateEname);
            if(isCheckExist("s_dictDataCate",whereMap,"")){
                log.error("科目标识重复："+cateEname);
                throw new BusinessException("科目标识重复："+cateEname);
            }
            param.put("dictDataCate.createTime",System.currentTimeMillis());
        }else if("i_dictDataItem".equals(modelTypes) || "u_dictDataItem".equals(modelTypes)){
            String cateEname = String.valueOf(param.get("dictDataItem.cateEname"));
            log.info("数据字典["+cateEname+"]["+typeMap.get(modelTypes)+"]->"+modelTypes);
            String itemId = "",fullCname = "",fullEname = "",fatherValue="0",subCount="0";
            if(modelTypes.indexOf("i_")>-1){
                //新增
                itemId = Validator.generate();
                param.put("dictDataItem.itemId",itemId);
                param.put("dictDataItem.createTime",System.currentTimeMillis());
            }else{
                //修改
                itemId = String.valueOf(param.get("dictDataItem.w_itemId"));
                param.put("dictDataItem.updateTime",System.currentTimeMillis());
            }
            String itemValue = String.valueOf(param.get("dictDataItem.itemValue"));
            whereMap.put("dictDataItem.w_itemValue",itemValue);
            whereMap.put("dictDataItem.w_cateEname",cateEname);
            if(isCheckExist("s_dictDataItem",whereMap,itemId)){
                log.error("条目标识重复："+itemValue);
                throw new BusinessException("条目标识重复："+itemValue);
            }

            //准备保存参数
            String itemText = String.valueOf(param.get("dictDataItem.itemText"));
            String fatherId = Validator.getDefaultStr(String.valueOf(param.get("dictDataItem.fatherId")), "0");//获取父节点ID，如果没有父节点，则默认0

            if ("0".equals(fatherId)) {//添加根条目，以及全层级
                fullCname = "/" + itemText;
                fullEname = "/" + itemId;
                subCount=Validator.getDefaultStr(String.valueOf(param.get("dictDataItem.subCount")),"0");
            }else{
                whereMap=new HashMap<>();
                whereMap.put("dictDataItem.w_itemId",fatherId);
                DataMap obj = getObj("s_dictDataItem",whereMap);
                if(obj!=null){
                    fullCname = StrUtil.doNull(String.valueOf(obj.get("fullCname")),"") + "/" + itemText;
                    fullEname = StrUtil.doNull(String.valueOf(obj.get("fullEname")),"") + "/" + itemId;
                    fatherValue = StrUtil.doNull(String.valueOf(obj.get("itemValue")),"");
                    subCount = StrUtil.doNull(String.valueOf(obj.get("subCount")),"0");
                }
            }
            param.put("dictDataItem.fatherValue",fatherValue);
            param.put("dictDataItem.fullCname",fullCname);
            param.put("dictDataItem.fullEname",fullEname);
            param.put("dictDataItem.subCount",subCount);

            //新增条目时，若是新增子项。则累加父对象字段
            if("i_dictDataItem".equals(modelTypes) && !fatherId.equals("0")) {
                saveSubCount(fatherId,true);
            }
        }else if("d_dictDataItem".equals(modelTypes)){
            String itemId = String.valueOf(param.get("dictDataItem.w_itemId"));
            String cateEname = String.valueOf(param.get("dictDataItem.w_cateEname"));
            log.info("数据字典["+cateEname+"]["+typeMap.get(modelTypes)+"]->"+modelTypes);
            String fatherId = String.valueOf(param.get("dictDataItem.w_fatherId"));
            whereMap.put("dictDataItem.w_fatherId",itemId);
            whereMap.put("dictDataItem.w_cateEname",cateEname);
            if(isCheckExist("s_dictDataItem",whereMap,"")){
                log.info("此["+cateEname+"]["+itemId+"]条目存在子元素，暂不能删除！");
                throw new BusinessException("存在子元素，暂不能删除！");
            }
            saveSubCount(fatherId,false);
        }else if("d_dictDataCate".equals(modelTypes)){
            String cateEname = String.valueOf(param.get("dictDataCate.w_cateEname"));
            log.info("数据字典["+cateEname+"]["+typeMap.get(modelTypes)+"]->"+modelTypes);
            whereMap.put("dictDataItem.w_cateEname",cateEname);
            if(isCheckExist("s_dictDataItem",whereMap,"")){
                log.info("此数据字典["+cateEname+"]存在子条目，暂不能删除！");
                throw new BusinessException("存在子条目，暂不能删除！");
            }
        }
        return param;
    }

    @Override
    public Object doInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub

        return null;
    }

    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }

    /**
     * 判断是否存在
     * @param searchObjName
     * @param whereMap
     * @return
     */
    private boolean isCheckExist(String searchObjName,Map<String,Object> whereMap,String id){
        String dataSource="plateform";
        ResultEntity resultEntity =(ResultEntity)IusPluginUtil.getInstance().select(dataSource,"list",searchObjName, whereMap);
        List<DataMap> list = new ArrayList<>();
        if(resultEntity!=null && resultEntity.getEntity()!=null){
            list = (List<DataMap>)resultEntity.getEntity();
        }
        boolean result = list.size()>0;
        if(result && StrUtil.isNotNull(id)){
            DataMap obj = list.get(0);
            if(id.equals(String.valueOf(obj.get("itemId")))){//排除修改是的自己
                result = false;
            }
        }
        return result;
    }

    /**
     * 修改父级条目子节点个数
     * @param fatherId
     */
    private void saveSubCount(String fatherId,boolean isAdd){
        Map<String,Object> whereMap = new HashMap<String,Object>();
        whereMap.put("dictDataItem.w_fatherId",fatherId);
        long subCount =0 ;
        String dataSource="plateform";
        ResultEntity resultEntity =(ResultEntity)IusPluginUtil.getInstance().select(dataSource,"count","s_dictDataItem", whereMap);
        if(resultEntity!=null && resultEntity.getEntity()!=null){
            subCount = (Long) resultEntity.getEntity();
        }
        if(isAdd){
            subCount++;
        }else{
            subCount--;
        }
        subCount=subCount<1?0:subCount;
        log.info("修改父级条目子节点个数：subCount->"+subCount);
        whereMap = new HashMap<String,Object>();
        whereMap.put("dictDataItem.w_itemId",fatherId);
        whereMap.put("dictDataItem.subCount",subCount);
        ResultEntity resultEntity_2 =(ResultEntity)IusPluginUtil.getInstance().saveInvoke(dataSource,"u_dictDataItem",whereMap);
        log.info("修改父级条目子节点个数："+ JSONObject.fromObject(resultEntity_2).toString());
    }
    //查找对象
    private DataMap getObj(String searchObjName,Map<String,Object> whereMap){
        String dataSource="plateform";
        ResultEntity resultEntity =(ResultEntity)IusPluginUtil.getInstance().select(dataSource,"obj",searchObjName, whereMap);
        DataMap obj = null;
        if(resultEntity!=null && resultEntity.getEntity()!=null){
            obj = (DataMap) resultEntity.getEntity();
        }
        return obj;
    }
}
